<template>
       <ul class='list'>
           <li 
             class="item" 
             v-for="item of letters" 
             :key="item"
             :ref="item"
             @click="handleLetterClick"
             @touchstart.prevent="hangdleTouchStart"
             @touchmove="hangdleTouchMove"
             @touchend="hangdleTouchMove"
            >
               {{item}}
            </li>
       </ul>
</template>

<script>
export default {
    name:'CityAlphabet',
     props:{
        cities:Object
    },
    data(){
        return{
            touchstart:false,
            startY:'',
            timer:null
        }
    },
    computed:{
        //把A,B,C...放数组里去
        letters(){
            const letters=[];
            for(let i in this.cities){
                letters.push(i)
            }
            return letters;
        }
    },
    updated(){
        this.startY=this.$refs['A'][0].offsetTop;//性能优化
    },
    methods:{
        handleLetterClick(e){
            this.$emit('change',e.target.innerText)
        },
        hangdleTouchStart(){//按下
            this.touchstart=true
        },
        hangdleTouchMove(e){//滑动
            if( this.touchstart){
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer=setTimeout(()=>{//性能优化
                    // const startY=this.$refs['A'][0].offsetTop;
                    const touchY=e.touches[0].clientY-79;
                    const index=Math.floor((touchY-this.startY)/20)
                    if(index>=0&&index<=this.letters.length){
                        this.$emit('change',this.letters[index])
                    }
                },16)
            }
        },
        hangdleTouchEnd(){//松开
             this.touchstart=false
        }
    }
}
</script>

<style scoped>
.list{
    display: flex;
    flex-direction: column;
    justify-content:center;
    position:absolute;
    right:0;
    bottom:0;
    top:1.58rem;
}
.item{
    line-height: 0.4rem;
    text-align: center;
    color:#00bcd4;
}
</style>